Repository navigation
Fix #5459 (Detect endless for loops) - #9038
willgarvin wants to merge 9 commits into
Conversation
…oops) Fix cppcheck-opensource#5459 Detect Endless For Loops
…5459-(Detect-Endless-For-Loops)
Co-authored-by: Cursor <cursoragent@cursor.com>
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found several false positives that I reproduced. The new missingForLoopIncrement warning (severity warning) fires on loops that do terminate, in three cases:
- The step clause updates the variable through a call, like
inc(&i),std::advance(it, 1)ors.step(i).stepUpdatesVaronly looks for++/--/assignment operators, andfindExpressionChangedonly searches the body. - The loop condition depends on something else that changes, like
i < nwithn--in the body,i != get(), ori < *pwithvolatile int *p. The check only asks whether the loop variable changes. - The body ends the program by calling a noreturn function, like
exit(1)or a[[noreturn]]function.hasForLoopExitonly recognisesgoto,return,throwandbreak.
The tests the PR adds don't cover any of these cases.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Step clause that updates the variable through a call gives a false positive | AI review | lib/checkother.cpp:5010 |
🆕 New |
| 2 | Other operands of the condition can change, e.g. i < n with n-- in the body |
AI review | lib/checkother.cpp:5013 |
🆕 New |
| 3 | noreturn calls (exit, abort, [[noreturn]] functions) are not counted as a loop exit | AI review | lib/checkother.cpp:4940 |
🆕 New |
@willgarvin, please fix, resolve or reply to the open and new comments: #1, #2, #3.
Testing
I built cppcheck and testrunner in /work/pr.
./testrunner TestOther: 0 tests failed.pytest other_test.py -k active_unusedfunction: 4 passed.
I ran ./cppcheck -q --enable=warning --library=std <file> on test files I wrote. Each of the following reports warning: The loop variable 'i' (or 'it') is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement], and in each case the warning is false. I didn't build base/: the check is new, so base can't report it.
// t1.cpp – step clause updates i through a call
void inc(int* p);
void f1(int n) { for (int i = 0; i < n; inc(&i)) {} }
// t2.cpp
#include <iterator>
#include <list>
void f2(std::list<int>& l) { for (auto it = l.begin(); it != l.end(); std::advance(it, 1)) {} }
// t7.cpp
struct S { void step(int& i); };
void f7(S& s, int n) { for (int i = 0; i < n; s.step(i)) {} }
// t14.cpp – lambda in step
void f14(int n) { for (int i = 0; i < n; ([&]{ i++; })()) {} }// t3.cpp – the other operand of the condition changes
void use(int);
void f3(int n) { for (int i = 0; i < n;) { use(i); n--; } }
// t5.cpp
int get();
void f5() { for (int i = 0; i != get();) {} }
// t8.cpp
void f8(volatile int *p) { for (int i = 0; i < *p;) {} }// t4.c – noreturn call ends the program
#include <stdlib.h>
void use(int);
void f4(int n) { for (int i = 0; i < n;) { use(i); exit(1); } }
// t10.cpp: same with a user [[noreturn]] void fail(); in the bodyOutput, for example: t3.cpp:3:5: warning: The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement].
These cases behave correctly:
- A lambda in the body that changes
iby reference: no warning. int *p = &i; *p += 1;in the body: no warning.- A condition joined with
&&: no warning. - A loop whose body only does
continue: warning, and that loop really is endless.
Automated review of d4960e1 by Claude. The pull request was built and tested locally.
|
Test results for commit d4960e1 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9038/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
|
Addressed review comments. Ready for another look. |
Co-authored-by: Cursor <cursoragent@cursor.com>
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
The fixes for the earlier review comments work: calls in the step, a changing bound and noreturn calls are now handled. I found one new class of false positive. The check still warns when the loop variable itself can be changed outside the code it sees:
- a
volatilecontrol variable whose address was passed out before the loop - a
std::atomic<int>that a thread captured by reference - a variable whose address was stored in a global pointer before the loop
The bound is now checked for volatile reads, but the control variable is not checked for volatile, atomic or address-taken. Apart from that, I found no new problems.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Step clause that updates the variable through a call gives a false positive | AI review | lib/checkother.cpp:5010 |
✅ Fixed |
| 2 | Other operand of the condition can change (n--, get(), volatile *p) | AI review | lib/checkother.cpp:5079 |
✅ Fixed |
| 3 | noreturn calls (exit, abort, [[noreturn]]) not counted as a loop exit | AI review | lib/checkother.cpp:4971 |
✅ Fixed |
| 4 | Volatile/atomic or address-escaped control variable gives a false positive | AI review | lib/checkother.cpp:5040 |
🆕 New |
@willgarvin, please fix, resolve or reply to the open and new comments: #4.
Testing
Build and tests
- I built
cppcheckandtestrunnerin /work/pr. ./testrunner TestOther: 256 tests, 0 failed.pytest other_test.py -k active_unusedfunction: 4 passed.- I didn't build base/: the check is new, so base can't report it.
False positives (../pr/cppcheck -q --enable=warning --library=std <file>)
// a2.c – volatile control variable; its address escapes before the loop
void register_flag(volatile int *p);
void f2(void) {
volatile int done;
register_flag(&done);
for (done = 0; done == 0;) {}
}a2.c:5:5: warning: The loop variable 'done' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]
// a1.cpp – atomic changed by another thread
#include <atomic>
#include <thread>
void f1() {
std::atomic<int> i;
std::thread t([&]{ i = 10; });
for (i = 0; i < 10;) {}
t.join();
}a1.cpp:6:5: warning: The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]
// a4.c – address stored in a global pointer, then changed through a call
int *g;
void tick(void) { (*g)++; }
void f4(int n) { int i; g = &i; for (i = 0; i < n;) tick(); }a4.c:3:... warning: The loop variable 'i' is not updated in this for-loop ... [missingForLoopIncrement]
Cases that behave correctly (no warning)
- A lambda that captures by reference, defined before the loop and called in the body.
- A global bound decremented through a called function.
- A member bound changed through a member call.
- A struct bound changed through a call that gets a pointer to the struct.
- A bound changed through a pointer alias.
longjmpin the body.
A loop whose body only does continue gets the warning, and that loop really is endless.
Automated review of ee9270e by Claude. The pull request was built and tested locally.
| return false; | ||
| if (!tok->valueType()) | ||
| return true; // incomplete type info; still allow for C / missing VT | ||
| return tok->valueType()->isIntegral() || tok->valueType()->type == ValueType::Type::ITERATOR; |
There was a problem hiding this comment.
AI review
The bound is checked for volatile reads, but the control variable is not. Its address can also escape before the loop, and that is not checked either. These loops get a false missingForLoopIncrement:
void register_flag(volatile int *p);
void f2(void) { volatile int done; register_flag(&done); for (done = 0; done == 0;) {} }void f1() { std::atomic<int> i; std::thread t([&]{ i = 10; }); for (i = 0; i < 10;) {} t.join(); }int *g; void tick(void) { (*g)++; }
void f4(int n) { int i; g = &i; for (i = 0; i < n;) tick(); }The std::atomic<int> case gets through because a missing or non-integral valueType is accepted here.
Suggested fix:
- Reject volatile control variables.
- Reject class types such as
std::atomic. - Bail out when the variable's address or a reference to it was taken before the loop and the body contains a call, for example with
isVariableChanged/isAliased.
|
Test results for commit ee9270e (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9038/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
New warning
missingForLoopIncrementto identify for loops whose control variable is never updated (ticket #5459 on Trac)Added brief documentation in
man/checkers/missingForLoopIncrement.md